package lottery;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomUtils;

public class LotteryServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		save(request);
		LotteryProd prod = getATry(request);
		System.out.println(prod.getPrize());
	}

	public List<LotteryProd> read(HttpServletRequest request) throws IOException {
		String dir = request.getSession().getServletContext().getRealPath("/test.json");
		File file = new File(dir);
		String json = FileUtils.readFileToString(file, "utf-8");
		System.out.println(json);
		List<LotteryProd> prods = JSONObject.parseArray(json, LotteryProd.class);
		return prods;
	}

	public void save(HttpServletRequest request) throws IOException {
		LotteryProd prod1 = new LotteryProd(1, LotteryProd.Type.NOTHING, "100", 100, 1, "1",1);
		LotteryProd prod2 = new LotteryProd(2, LotteryProd.Type.NOTHING, "100", 100, 1, "2",2);
		LotteryProd prod3 = new LotteryProd(3, LotteryProd.Type.NOTHING, "200", 100, 0, "3",3);
		LotteryProd prod4 = new LotteryProd(4, LotteryProd.Type.NOTHING, "200", 100, 0, "4",4);
		LotteryProd prod5 = new LotteryProd(5, LotteryProd.Type.NOTHING, "200", 100, 0, "5",5);
		List<LotteryProd> prods = new ArrayList();
		prods.add(prod1);
		prods.add(prod2);
		prods.add(prod3);
		prods.add(prod4);
		prods.add(prod5);
		JSONArray array = new JSONArray();

		for (LotteryProd prod : prods) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("prod", prod);
			array.add(jsonObject);
		}
		String s = array.toJSONString();
		System.out.println(s);
		String dir = request.getSession().getServletContext().getRealPath("/test.json");
		File file = new File(dir);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file);
		PrintWriter pw = new PrintWriter(fw);
		pw.write(s);
		fw.close();
		pw.close();
	}

	private LotteryProd getATry(HttpServletRequest request) throws IOException {
		long sum = getSum(request);
		long num = RandomUtils.nextLong(0, sum);

		List<LotteryProd> prods = read(request);
		for (LotteryProd prod : prods) {
			if (num < prod.getOdds()) {
				return prod;
			}
			num -= prod.getOdds();
		}
		return null;
	}

	private long getSum(HttpServletRequest request) throws IOException {
		List<LotteryProd> prods = read(request);
		long sum = 0;
		for (LotteryProd prod : prods) {
			sum += prod.getOdds();
		}
		return sum;
	}
}
